<?php
namespace app\admin\controller;

use think\Controller;
use think\Cookie;
use think\Db;
use think\Request;
use think\Session;

class Login extends Controller
{
    public function index()
    {
        if(is_login()){
            $this->redirect('index/index');
        }
        $request=Request::instance();
        if($request->isAjax()){
            $mode_amdin=Db::name('admin');
            $username=input('post.admin_username','','op_t');
            $password=input('post.admin_pwd','','op_t');
            //是否记住密码
            $remember=input('post.remember','','intval');
            if(empty($username)||empty($password)){
                $this->error("参数错误");
            }
            $map['admin_username']=$username;
            $map['admin_pwd']=md5_password($password);
            $map['status']=1;
            $admin=$mode_amdin->where($map)->find();
            if (!$admin||$map['admin_pwd']!==$admin['admin_pwd']){
                $this->error('用户名或者密码错误，重新输入');
            }else{
                //登录后更新数据库，登录IP，登录次数,登录时间
                $ip=get_client_ip();
                $mode_amdin->where('id', $admin['id'])->setInc('admin_hits');
                $mode_amdin->where('id', $admin['id'])->update(['admin_ip' => $ip]);
                unset($admin['admin_pwd']);
                Session::set('admin_auth',$admin);
                if($remember){
                    Cookie::set('admin_auth',$admin,86400);// 指定cookie保存时间1天
                }
                $this->success('恭喜您，登陆成功');
            }
        }
        return view('login');
    }
   /*
    * 退出
    * */
    public function logout(){
        if(is_login()){
            Session::delete('admin_auth');
            Cookie::delete('admin_auth');
            $this->redirect('login/index');
        }else{
            $this->redirect('login/index');
        }
    }
}
